package ming.listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener
public class OnlineCountListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        //要想统计session，作用域要提到最高
        ServletContext servletContext = httpSessionEvent.getSession().getServletContext();
        System.out.println(httpSessionEvent.getSession().getId());
        Integer onlinecount = (Integer) servletContext.getAttribute("OnlineCount");
        Integer c = (Integer) servletContext.getAttribute("countSum");

        if (onlinecount == null) {
            onlinecount = new Integer(0); //用int也行，这里用的是封装整型类的操作，等价于onlinecount = 1;
            c = 0;
        } else {
            int count = onlinecount.intValue();
            onlinecount = new Integer(count + 1); //等价于 onlinecount += 1;
            ++c;
        }
        //每次都在更新自己,有累加
        servletContext.setAttribute("OnlineCount", onlinecount);
        servletContext.setAttribute("countSum", c);
    }

    //销毁session监听
    //一旦session销毁，就会触发
    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        ServletContext servletContext = httpSessionEvent.getSession().getServletContext();
        Integer onlinecount = (Integer) servletContext.getAttribute("OnlineCount");

        if (onlinecount == null) {
            onlinecount = new Integer(0);
        } else {
            int count = onlinecount.intValue();
            onlinecount = new Integer(count - 1);
        }
        System.out.println("---------");
        //每次都在更新自己,有累加
        servletContext.setAttribute("OnlineCount", onlinecount);
    }
}
